import { join } from "path";
import { BrowserWindow, Menu, Tray, app, ipcMain } from "electron";
import { enable as enableRemote, initialize } from "@electron/remote/main";

// Disable GPU Acceleration for Windows 7
app.disableHardwareAcceleration();
app.commandLine.appendSwitch("disable-gpu");
app.commandLine.appendSwitch("no-sandbox");
app.commandLine.appendSwitch("disable-gpu-sandbox");
app.commandLine.appendSwitch("disable-direct-composition");
// Set application name for Windows 10+ notifications
if (process.platform === "win32") app.setAppUserModelId(app.getName());
initialize();
export const ROOT_PATH = {
  // /dist
  dist: join(__dirname, app.isPackaged ? "../dist" : "../"),
  // /dist or /public
  public: join(__dirname, app.isPackaged ? "../dist" : "../public"),
};

let win: BrowserWindow | null = null;
let tray: Tray | null = null;

if (!app.requestSingleInstanceLock()) {
  app.quit();
  process.exit(0);
} else {
  app.on("second-instance", () => {
    if (win) {
      if (win.isMinimized()) win.restore();
      win.maximize();
      win.show();
      win.setSkipTaskbar(false);
      win.focus();
    }
  });
}

const indexHtml = join(ROOT_PATH.dist, "index.html");

async function createWindow() {
  win = new BrowserWindow({
    title: "EVE工具",
    fullscreenable: true,
    autoHideMenuBar: true,
    icon: join(ROOT_PATH.public, "logo.png"),
    webPreferences: {
      backgroundThrottling: false,
      webSecurity: false,
      allowRunningInsecureContent: false,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      contextIsolation: false,
      sandbox: false,
      webviewTag: true,
      devTools: true,
    },
  });
  enableRemote(win.webContents);
  if (app.isPackaged) {
    await win.loadFile(indexHtml);
  } else {
    // 🚧 Use ['ENV_NAME'] avoid vite:define plugin
    const port = import.meta.env.VITE_DEV_SERVER_PORT;
    const url = `http://localhost:${port}/`;
    await win.loadURL(`${url}index.html`);
  }
  win.on("close", (event) => {
    win?.hide();
    win?.setSkipTaskbar(true);
    event.preventDefault();
  });
  win.on("closed", () => {
    win = null;
  });
  const contextMenu = Menu.buildFromTemplate([
    {
      id: "exit",
      label: "退出",
      click: () => {
        win?.destroy();
      },
    },
    //我们需要在这里有一个真正的退出（这里直接强制退出）
  ]);
  //托盘
  tray = new Tray(join(ROOT_PATH.public, "logo.png"));
  tray.setToolTip("EVE工具");
  tray.setContextMenu(contextMenu);
  tray.on("click", () => {
    if (win?.isMinimized()) {
      win?.maximize();
      win?.show();
    } else {
      if (win?.isVisible()) {
        win?.hide();
      } else {
        win?.maximize();
        win?.show();
      }
    }
    win?.setSkipTaskbar(false);
  });
}

app.on("window-all-closed", () => {
  win = null;
});
app.whenReady().then(createWindow);

ipcMain.on("browser-message", (event, data) => {
  if (data.event === "max-windows") {
    if (win?.isMinimized()) {
      win?.maximize();
      win?.show();
    }
  }
});
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", async () => {
  if (win === null) {
    await createWindow();
  } else {
    if (win.isMinimized()) {
      win.maximize();
      win.show();
      win.setSkipTaskbar(false);
    }
    win.focus();
  }
});
